package cn.sc.summer.mybatis.context;

import cn.sc.summer.constant.mybatisplus.TenantInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * 以静态变量保存租户信息
 *
 * @author a-xin
 */
@Slf4j
@Component
public class TenantContextHolder implements DisposableBean {

    /**
     * 租户信息
     */
    private static final ThreadLocal<TenantInfo> TENANT_INFO = new ThreadLocal<>();

    /**
     * 获取租户信息
     */
    public static TenantInfo getTenantInfo() {
        return TENANT_INFO.get();
    }

    /**
     * 存储租户信息
     */
    public static void setTenantInfo(TenantInfo tenantInfo) {
        if (tenantInfo.getIgnoreTenant()) {
            log.debug("-> tenant ignore: true");
        } else {
            log.debug("-> tenant ignore: false, tenantId: {}", tenantInfo.getTenantId());
        }
        TENANT_INFO.set(tenantInfo);
    }

    /**
     * 清除租户信息
     */
    public static void clearTenantInfo() {
        Optional.ofNullable(TENANT_INFO.get()).ifPresent(info -> log.debug("-> clear the tenant info: {}", info.getTenantId()));
        TENANT_INFO.remove();
    }

    /**
     * Invoked by the containing {@code BeanFactory} on destruction of a bean.
     */
    @Override
    public void destroy() {
        TenantContextHolder.clearTenantInfo();
    }

}
